package com.asset.inventory.base

import android.app.Activity
import android.app.Application
import android.os.Bundle
import com.asset.inventory.utils.MyCrashHandler


/**
 *    @author : sibb
 *    date   : 21-3-16
 *    desc   : 应用
 */
class BaseApp: Application() {

    private val myActivitys: ArrayList<Activity> = ArrayList()

    private var topActivity: Activity? = null

    companion object {
        lateinit var instance: BaseApp
    }

    //是否为在线模式
    var isOnlineModel = false

    public val isTest = false

    val isLoaderRfidSdk = true


    override fun onCreate() {
        super.onCreate()
        instance = this
        val handler = MyCrashHandler()
        Thread.setDefaultUncaughtExceptionHandler(handler)
        registerActivityListener()
    }

    /**
     * 注册监听activity的创建和销毁
     */
    fun registerActivityListener() {
        registerActivityLifecycleCallbacks( object: ActivityLifecycleCallbacks {
            override fun onActivityPaused(p0: Activity) {

            }

            override fun onActivityStarted(p0: Activity) {
            }

            override fun onActivityDestroyed(p0: Activity) {
                removeActivity(p0)
            }

            override fun onActivitySaveInstanceState(p0: Activity, p1: Bundle) {

            }

            override fun onActivityStopped(p0: Activity) {

            }

            override fun onActivityCreated(p0: Activity, p1: Bundle?) {
                addActivity(p0)
            }

            override fun onActivityResumed(p0: Activity) {
                topActivity = p0

            }
        })

    }



    fun finishAllActivity() {
        if (myActivitys.isEmpty()) {
            return
        }
        for (activity in myActivitys) {
            activity.finish()
        }
        myActivitys.clear()
    }


    /**
     * 从列表移除指定activity
     *
     * @param activity 移除的activity
     */
    fun removeActivity(activity: Activity) {
        if (myActivitys.isEmpty())
            return
        myActivitys.remove(activity);
    }

    /**
     * 添加activity到列表
     *
     * @param activity 添加的activity
     */
    fun  addActivity(activity: Activity) {
        myActivitys.add(activity);
    }

    /**
     * 应用在前台时，当前页面
     * @return
     */
    fun getTopActivity(): Activity? {
        return topActivity
    }








}